//
//  WFComposeVC.swift
//  WangFangWeiBo
//
//  Created by 王方 on 16/7/18.
//  Copyright © 2016年 wf. All rights reserved.
//

import UIKit
import SVProgressHUD

class WFComposeVC: UIViewController {
    
    // MARK:  - 懒加载控件
    
    //表情键盘
    private lazy var keyBoard:WFEmoticonKeyBoard = {
        let view = WFEmoticonKeyBoard()
        //设置视图大小
        view.size = CGSize(width: self.textView.width, height: 216)
        
        return view
    }()
    
    //textView上的pictureView
    private lazy var pictureView:WFComposePictureView = {
        let pictureView = WFComposePictureView()
        return pictureView
    }()
    
    
    //最下面的toolbar
    private lazy var toolBar:WFComposeToolBar = {
        let toolBar = WFComposeToolBar(frame: CGRectZero)
        return toolBar
    }()
    
    //中间的textView
    private lazy var textView:WFComposeTV = {
        //这里要自定义textView
    let textView = WFComposeTV()
        textView.delegate = self
        textView.placeHolder = "各种kimo,各种ji"
        
    
    textView.font = UIFont.systemFontOfSize(15)
    textView.alwaysBounceVertical = true
    return textView
    }()
    
    //最左边的发送按钮
    private lazy var sendBtn:UIButton = {
        let btn = UIButton()
        //  添加点击事件
        btn.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        btn.setTitle("发送", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        btn.size = CGSize(width: 45, height: 30)
        
        //这里的btn被UIBarButtonItem管理了,所以需要设置UIBarButtonItem的属性让btn一开始是不可用的才行
        
        return btn
    }()
    
    //正上方的用户名视图
    private lazy var titleLabel:UILabel = {

        
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 17)
 
        label.numberOfLines = 0
        label.textAlignment = .Center
        //获取用户名
        if let name = WFUserAccountViewModel.sharedUserAccount.userAccount?.name {
            
            let title = "发微博\n\(name)"
            let attributeStr = NSMutableAttributedString(string: title)
            let range = (title as NSString).rangeOfString(name)
            attributeStr.addAttributes([NSForegroundColorAttributeName: UIColor.lightGrayColor(), NSFontAttributeName: UIFont.systemFontOfSize(12)], range: range)
            label.attributedText = attributeStr
            
        }else{
            label.text = "发微博"
        }
        
        //这句话一定要设置,不然就显示不了,一般用于懒得设置frame的细小的地方
        label.sizeToFit()
        
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpUI()
    }

   // MARK:  - 初始化
    private func setUpUI(){
        view.backgroundColor = UIColor.whiteColor()
        

        //  监听键盘改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //监听点击按钮的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectedEmoticon:", name: DidSeletedEmotionButtonNotification, object: nil)
        //监听删除按钮的点击
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didDeleteSelectedEmoticon", name: DidSelecteDeleteEmoticonButtonNotification, object: nil)
        setUpNav()
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        //添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(view)
            make.leading.equalTo(view)
            make.height.equalTo(35)
            make.bottom.equalTo(view)
        }
        
        // MARK:  - 底部点击toolbar的闭包设置
        toolBar.clickOnToolBarBtnClosure = { [weak self](type:WFComposeToolBarBtnType) in
            switch type {
            case .Picture:
                print("图片")
                self?.clickOnPictureView()
            case .Mention:
                print("@")
            case .Trend:
                print("话题")
            case .Emoticon:
                print("表情")
                self!.clickOnEmoticon()
            case .Add:
                print("加号")
            }

            
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.leading.equalTo(textView).offset(10)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        // MARK:  - 添加图片按钮的闭包,注意要避免循环引用
        pictureView.clickOnAddBtnClosure = { [weak self] in
            self?.clickOnPictureView()
        }
    }
    
    // MARK:  - 初始化nav
    private func setUpNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancel")
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem  = UIBarButtonItem(customView: sendBtn)
        navigationItem.rightBarButtonItem?.enabled = false
    }

    // MARK:  - 左上角点击取消的按钮方法
    @objc private func cancel(){
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK:  - 右上角的发送按钮的方法
    @objc private func sendAction(){
         if pictureView.images.count > 0 {
            upload()
        } else {
           update()
        }
        
        
       
        
        
    }

    // MARK:  - 上传图片的方法
private func upload(){
   
        let image = pictureView.images.first!
        let accessToken = WFUserAccountViewModel.sharedUserAccount.accessToken!
        let text = textView.emoticonStr
        SVProgressHUD.show()
        WFNetWorkTools.sharedTools.upload(accessToken, status: text, image: image, callBack: { (response, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }else {
                //  发送成功
                SVProgressHUD.showSuccessWithStatus("发送成功")
            }
            
        })
}
    
    // MARK:  - 发送文字
    private func update(){
        //现在只发送文字
        let contentStr = textView.emoticonStr
        let access_token = WFUserAccountViewModel.sharedUserAccount.userAccount?.access_token
        WFNetWorkTools.sharedTools.upload(access_token!, status: contentStr) { (response, error) -> () in
            if error != nil {
                print(error)
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            
            
            //  发送成功
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }

    // MARK:  - 删除按钮的点击事件
    @objc private func didDeleteSelectedEmoticon(){
        //删除一个
        textView.deleteBackward()
    }
    
    // MARK:  - 表情键盘的点击事件
    @objc private func didSelectedEmoticon(noti:NSNotification){
        let emoticon =  noti.object as! WFEmoticon
        // MARK:  - 定义textView的方法
        textView.insertEmoticon(emoticon)
    }
    
    // MARK:  - 键盘的frame改变事件
    @objc private func keyboardChangeFrame(noti:NSNotification){
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //获取动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - ScreenHeight)
        }
        //  执行动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
}

// MARK:  - 照片相册的代理以及事件
extension WFComposeVC:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    // MARK:  - 点击了表情按钮
    func clickOnEmoticon(){
        if textView.inputView == nil {
            //设置为表情键盘
            textView.inputView = keyBoard
            //改变图标
            toolBar.showEmotionIcon(true)
            
        } else {
            //设置为系统键盘
            textView.inputView = nil
            toolBar.showEmotionIcon(false)
        }
    
        textView.becomeFirstResponder()
        textView.reloadInputViews()
    }
    
    
    // MARK:  - 点击了第一个添加图片的按钮
     func clickOnPictureView(){
        //弹出相册
        let imagePictureCtr = UIImagePickerController()
        imagePictureCtr.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            imagePictureCtr.sourceType = .Camera
             print("支持相机")
        } else {
            imagePictureCtr.sourceType = .PhotoLibrary
            print("不支持相机,使用的图库")

        }
        
        //  判断是否支持前置或者后者摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("支持前置摄像头")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("支持后置摄像头")
        } else {
            print("前后置摄像头不支持")
        }
        
        //  允许用户编辑
        //imagePictureCtr.allowsEditing = true
        
        presentViewController(imagePictureCtr, animated: true, completion: nil)
    }
    
    //选择完毕后的回调
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
         let scaleImage = image.scaleImageWithScaleWidth(200)
        
        pictureView.addImage(scaleImage)
        //必须手动重写才可以返回
        dismissViewControllerAnimated(true, completion: nil)
    }
    //必须手动重写才可以返回
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }

}

// MARK:  - textView的代理
extension WFComposeVC: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //  根据文本内容判断发送按钮是否可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
    }
    
}
